<template>
    <!-- 添加角色表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%" @close="handleClose">
        <el-form label-width="120px" ref="formRef" :model="form" :rules="rules">

            <el-form-item label="品牌名称" prop="name">
                <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="logo" prop="logo">
                <el-upload class="avatar-uploader" action="/api/admin/system/fileUpload" @success="handleSuccess"
                    :headers="headers" :show-file-list="false">
                    <img v-if="form.logo" :src="form.logo" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                    </el-icon>
                </el-upload>
            </el-form-item>
       

            <el-form-item>
                <el-button type="primary" @click="handleSubmit()">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script lang="ts" setup>

import { ref } from 'vue'
import type { Brand } from '../impl';

import { useUserStore } from '@/stores/index.ts'
const headers = {
    "X-Token": useUserStore().token     // 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
}

// 控制对话是否展示的变量
const dialogVisible = ref(false)
const formRef = ref()

const emit = defineEmits(['submit'])
const props = defineProps({
    title: String,
})
const defaultForm = {
    id: null,
    name: "",
    logo: "",

}


const form = ref<Brand>(defaultForm)
// 定义提交表单数据模型

const rules = ref({
    name: [
        { required: true, message: '请输入品牌名称', trigger: 'blur' },

    ],
    logo: [
        { required: true, message: '请上传logo', trigger: 'blur' },
    ],

 


})

const handleSuccess = (res: any) => {

    form.value.logo = res.data
}

const handleClose = () => {
    form.value = defaultForm

}

//进入添加
const show = (data: Brand) => {
    dialogVisible.value = true
 
    if (data && data.id) {
        form.value = { ...data } as Brand
    } else {
        form.value = defaultForm
    }
}

const handleSubmit = () => {
    formRef.value.validate((valid: boolean) => {
        if (valid) {
            dialogVisible.value = false
            emit('submit', form.value)
        }
    })

}



defineExpose({
    show
})
</script>
<style scoped>
.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>